package com.cmes.mes.basic.core.biz;

import com.cmes.core.exception.FrameworkException;
import com.cmes.mes.audit.constant.BusinessEnum;
import com.cmes.mes.audit.service.GenericBusinessService;
import com.cmes.mes.audit.service.SnGenerateService;
import com.cmes.mes.basic.core.entity.VendorEntity;
import com.cmes.mes.basic.core.repository.VendorRepository;
import com.cmes.mes.basic.core.service.VendorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 客户管理
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class VendorBizService extends
        GenericBusinessService<VendorService, VendorRepository, VendorEntity> {

    private final SnGenerateService snGenerateService;
    private final BusinessEnum business = BusinessEnum.VENDOR;

    @Override
    protected BusinessEnum getBusiness() {
        return business;
    }

    @Override
    protected void beforeAdd(VendorEntity entity) {
        entity.setCode(snGenerateService.generate(getBusiness().getCode()));
        entity.setId(Long.parseLong(entity.getCode()));
        initAuditProperty(entity);
    }

    @Override
    protected void afterAdd(VendorEntity entity) {
        if (!business.getAudit()) {
            getGenericService().removeCache();
        }
    }

    @Override
    protected void afterUpdate(VendorEntity entity, VendorEntity db) {
        if (!business.getAudit()) {
            getGenericService().removeCache();
        }
    }

    @Override
    protected void afterDelete(List<Long> ids, List<VendorEntity> dbs) {
        if (!business.getAudit()) {
            getGenericService().removeCache();
        }
    }

    @Override
    protected void afterAudit(List<Long> ids, List<VendorEntity> entities) {
        // 清理缓存
        getGenericService().removeCache();
        // 自动注册会计凭证
        autoRegisterFinanceVoucher(entities);
    }

    @Override
    public List<VendorEntity> canReAudit(List<Long> ids) {
        throw new FrameworkException("不支持该功能");
    }

    @Override
    protected void afterDisable(List<Long> ids, List<VendorEntity> entities) {
        getGenericService().removeCache();
    }

    /**
     * TODO 自动注册会计凭证
     */
    private void autoRegisterFinanceVoucher(List<VendorEntity> entities) {
    }

}
